package com.ht.sps.util;

import org.apache.commons.lang3.text.StrSubstitutor;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by bcw on 14-1-25.
 */
public class MessageFormatUtil {
    /**
     * 采用名称占位符方式格式化字符串
     * @param tpl 字符串模板
     * @param params 名称占位符对应值, key为变量名称，value为显示的字符串
     * @return
     */
    public static String format(String tpl, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return tpl;
        }
        StrSubstitutor sub = new StrSubstitutor(params, "{", "}");
        String result = sub.replace(tpl);
        return result;
    }

    /**
     *
     * @param tpl
     * @param params
     * @return
     */
    public static String format2(String tpl, Map<String, Object> params) {
        if (params == null || params.isEmpty()) {
            return tpl;
        }
        Map<String, String> map = new HashMap(params.size());

        for (Map.Entry<String, Object> entry : params.entrySet()) {

            if (entry.getValue() != null) {
                map.put(entry.getKey(), entry.getValue().toString());
            }  else {
                map.put(entry.getKey(), "");
            }
        }
        return format(tpl, map);
    }
}
